package main

import (
	"context"
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

// if u take a token from limiter it will return to limiter after Limit Duration

func main() {
	// every 1 action per second, brust 1
	{
		limiter := rate.NewLimiter(1, 1)
		for i := 0; i < 5; i++ {
			if limiter.Allow() {
				fmt.Println("action start")
			} else {
				fmt.Println("action not allow")
			}
			time.Sleep(500 * time.Millisecond)
		}
	}

	fmt.Println("----------------------")

	// every 1 action per 100 millisecond, brust 5
	{
		limiter := rate.NewLimiter(rate.Every(100*time.Millisecond), 3)
		for i := 0; i < 6; i++ {
			t := time.Now().Truncate(time.Millisecond)
			err := limiter.Wait(context.TODO())
			if err != nil {
				panic(err)
			}
			fmt.Println("action wait cost: ", time.Now().Truncate(time.Millisecond).Sub(t))
		}

		time.Sleep(400 * time.Millisecond)

		for i := 0; i < 6; i++ {
			t := time.Now().Truncate(time.Millisecond)
			err := limiter.Wait(context.TODO())
			if err != nil {
				panic(err)
			}
			fmt.Println("action wait cost: ", time.Now().Truncate(time.Millisecond).Sub(t))
		}
	}
}
